package com.pdd.mall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.mall.common.api.CommonResult;
import com.pdd.mall.entity.Promotion;
import com.pdd.mall.service.PromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 促销活动控制器 - 用户端
 */
@RestController
@RequestMapping("/promotions")
public class PromotionController {

    @Autowired
    private PromotionService promotionService;

    /**
     * 获取所有进行中的促销活动
     */
    @GetMapping("/active")
    public CommonResult<List<Promotion>> getActivePromotions() {
        List<Promotion> activePromotions = promotionService.getActivePromotions();
        return CommonResult.success(activePromotions);
    }

    /**
     * 获取商品的促销信息
     */
    @GetMapping("/product/{productId}")
    public CommonResult<Map<String, Object>> getProductPromotion(@PathVariable Long productId) {
        Map<String, Object> promotionInfo = promotionService.getProductPromotion(productId);

        // 如果有促销活动，计算促销价格
        if ((Boolean) promotionInfo.get("hasPromotion")) {
            Promotion promotion = (Promotion) promotionInfo.get("promotion");

            // 如果是秒杀活动，直接从规则中获取秒杀价格
            if ("flash".equals(promotion.getType())) {
                try {
                    // 直接使用原价计算秒杀价格
                    BigDecimal originalPrice = new BigDecimal("299");
                    BigDecimal flashPrice = promotionService.calculatePromotionPrice(productId, originalPrice);
                    promotionInfo.put("promotionPrice", flashPrice);
                    System.out.println("商品ID: " + productId + " 的秒杀价格: " + flashPrice);
                } catch (Exception e) {
                    System.err.println("计算秒杀价格失败: " + e.getMessage());
                }
            } else {
                // 对于其他类型的促销，使用商品服务获取原价
                // 这里我们使用一个默认原价，因为我们只关心秒杀价格
                BigDecimal originalPrice = new BigDecimal("299");
                BigDecimal promotionPrice = promotionService.calculatePromotionPrice(productId, originalPrice);
                promotionInfo.put("promotionPrice", promotionPrice);
                System.out.println("商品ID: " + productId + " 的促销价格: " + promotionPrice);
            }
        }

        return CommonResult.success(promotionInfo);
    }
}
